
#include "Agent.h"
#include "AgentState.h"

Agent::Agent(tank_t* tank)
{
	this->tank = tank;
	currentState = 0;
	checkStuck = true;
	isStuck = false;
	turn = 1;
	stuck = 0;
	iterations = BACKUP;
	prevPos = Vector2(tank->pos[0], tank->pos[1]);
}


Agent::~Agent(void)
{
}

Command Agent::GetCommand(){
	if (currentState && tank->status == "alive"){
		if(checkStuck){
			if(isStuck){
				iterations --;
				if(iterations <= 0){
					isStuck = false;
					stuck = 0;
					iterations = BACKUP;
					turn *= -1;
				}
				return Command(tank->index, -1, turn, true);
			}
			else if(fabs(prevPos.x - tank->pos[0]) < POSITION_THRESHOLD &&
			   fabs(prevPos.y - tank->pos[1]) < POSITION_THRESHOLD){
				stuck++;
				if(stuck >= 30)
					isStuck = true;
			}
			else
				stuck = 0;
			prevPos = Vector2(tank->pos[0], tank->pos[1]);
		}
		return currentState->GetCommand(this);
	}

	return Command(this->tank->index, 0, 0, false);
}

tank_t* Agent::getTank(){
	return tank;
}

void Agent::setState(AgentState* newState, bool checkForStuck) {
	checkStuck = checkForStuck;
	
	if (currentState) {
		currentState->exit(this);
		delete currentState;
	}

	currentState = newState;

	if (currentState)
		currentState->enter(this);
}